package MicroSpring.beanPostProcessor.impl;

import MicroSpring.beanFactory.impl.DefaultListableBeanFactory;
import MicroSpring.beanPostProcessor.InstantiationAwareBeanPostProcessor;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/*
    处理bean 注入多例bean 为null的问题。
 */
public class LazyInjectBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
    private final DefaultListableBeanFactory beanFactory;

    public LazyInjectBeanPostProcessor(DefaultListableBeanFactory beanFactory) {
        this.beanFactory=beanFactory;
    }

    @Override
    public void postProcessProperties(Object bean, String beanName) {
        Map<String, List<Field>> lazyInjectBeans = this.beanFactory.getLazyInjectBeans();
        if (lazyInjectBeans.containsKey(beanName)) {
            List<Field> fs = lazyInjectBeans.get(beanName);
            for (Field f : fs) {
                Class<?> returnType = f.getType();
                try {
                    Object o = returnType.newInstance();
                    f.set(bean,o);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
